package com.sigmazero13.gameutils;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.sigmazero13.gameutils.db.UtilDbHelper;
import com.sigmazero13.gameutils.model.GameInfo;
import com.sigmazero13.gameutils.model.GamePlayInfo;
import com.sigmazero13.gameutils.model.GamePlayerInfo;
import com.sigmazero13.gameutils.utils.GameNameAdapter;
import com.sigmazero13.gameutils.widgets.MultiPlayerEntry;
import com.sigmazero13.gameutils.widgets.PlayerEntryView;

public class RecordGameConfig extends Activity {
	private Spinner gameSpinner;
	private DatePicker dateView;
	private EditText lengthView;
	private AutoCompleteTextView locationView;
	private AutoCompleteTextView scenarioView;
	private MultiPlayerEntry playerView;
	private Button recordButton;
	private UtilDbHelper dbHelper;
	private long playId = 0;
	private List<GameInfo> games;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.record_game);
		
		Bundle bundle = getIntent().getExtras();
		int gameId = 0;
		long gameLength = 0;
		if (bundle != null) {
			gameId = bundle.getInt("game_id", 0);
			playId = bundle.getLong("play_id", 0);
			gameLength = bundle.getLong("game_length", 0);
		}
		
		GamePlayInfo play = null;
		if (playId > 0) {
			play = ((BoardGameUtilsApp)RecordGameConfig.this.getApplication()).getDbHelper().selectSinglePlay(playId);
			gameId = play.getGame().getGameId();
		}
		
		games = ((BoardGameUtilsApp)RecordGameConfig.this.getApplication()).getDbHelper().selectAllGames(); 
		
		gameSpinner = (Spinner) findViewById(R.id.record_game_spinner);
		GameNameAdapter adapter = new GameNameAdapter(this, R.layout.list_item, games);
		adapter.setDropDownViewResource(R.layout.list_item);
		gameSpinner.setAdapter(adapter);
		if (gameId > 0) {
			setGame(gameId);
		} else {
			gameId = ((GameInfo)gameSpinner.getSelectedItem()).getGameId();
		}
		
		gameSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				updateAutocompletes((GameInfo)gameSpinner.getSelectedItem());
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				updateAutocompletes(null);
			}
		});
		
		dateView = (DatePicker) findViewById(R.id.record_date);
		locationView = (AutoCompleteTextView) findViewById(R.id.record_location);
		scenarioView = (AutoCompleteTextView) findViewById(R.id.record_scenario);
		lengthView = (EditText) findViewById(R.id.record_length);
		if (gameLength > 0) lengthView.setText(gameLength + "");
		
		dbHelper = ((BoardGameUtilsApp)getApplication()).getDbHelper();
		
		setLocationList(dbHelper.getLocations());
		setScenarioList(dbHelper.getScenariosForGame(gameId));
		
		playerView = (MultiPlayerEntry) findViewById(R.id.player_list);
		playerView.setPlayerList(dbHelper.getPlayerNames());
		playerView.setUsernameList(dbHelper.getPlayerUsernames());
		playerView.setTeamList(dbHelper.getTeamsForGame(gameId));
		
		recordButton = (Button) findViewById(R.id.record_play);
		recordButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				recordPlay();
			}
		});
		
		setPlayInfo(play);
		this.setResult(RESULT_CANCELED);
	}
	
	
	private void setPlayInfo(GamePlayInfo play) {
		if (play == null) return;
		
		setGame(play.getGame().getGameId());
		Date playDate = play.getGameDate();
		dateView.updateDate(playDate.getYear()+1900, playDate.getMonth(), playDate.getDate());
		locationView.setText(play.getLocation());
		scenarioView.setText(play.getScenario());
		lengthView.setText(play.getGameLength().toString());
		playerView.setPlayerInfo(play.getPlayers());
		
		recordButton.setText("Record changes");
	}
	

	private void setGame(int gameId) {
		for (int i = 0; i < games.size(); i++) {
			if (games.get(i).getGameId() == gameId) {
				gameSpinner.setSelection(i);
				break;
			}
		}
	}


	private GamePlayInfo buildPlayInfo() {
		GamePlayInfo play = new GamePlayInfo();
		play.setGame((GameInfo)gameSpinner.getSelectedItem());
		play.setGameDate(new GregorianCalendar(dateView.getYear(), dateView.getMonth(), dateView.getDayOfMonth()).getTime());
		try {
			play.setGameLength(Integer.parseInt(lengthView.getText().toString()));
		} catch (NumberFormatException nfe) {
			play.setGameLength(null);
		}
		play.setLocation(locationView.getText().toString());
		play.setScenario(scenarioView.getText().toString());
		
		List<PlayerEntryView> players = playerView.getAllInputs();
		for (PlayerEntryView playerView : players) {
			GamePlayerInfo player = new GamePlayerInfo();
			player.setName(playerView.getPlayerName());
			player.setUsername(playerView.getUsername());
			player.setTeam(playerView.getTeam());
			player.setStartingPos(playerView.getStartingPos());
			player.setScore(playerView.getScore());
			player.setWinner(playerView.getWinner());
			
			play.addPlayer(player);
		}
		
		return play;
	}
	
	private void recordPlay() {
		GamePlayInfo play = buildPlayInfo();
		int code = ((BoardGameUtilsApp)getApplication()).getDbHelper().recordPlay(play, playId);
		String toast = "";
		switch (code) {
		case UtilDbHelper.OPERATION_SUCCESS:
			toast = "Play recorded successfully!";
			break;
		case UtilDbHelper.OPERATION_SUCCESS_WITH_ERRORS:
			toast = "Play recorded, some players not recorded due to errors.";
			break;
		case UtilDbHelper.OPERATION_FAIL:
			toast = "Play recording failed.";
			break;
		}
		Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
		this.setResult(RESULT_OK);
		this.finish();
	}	
	
	private void updateAutocompletes(GameInfo game) {
		List<String> teams = null;
		if (game != null) {
			teams = dbHelper.getTeamsForGame(game.getGameId());
			setScenarioList(dbHelper.getScenariosForGame(game.getGameId()));
		}
		playerView.setTeamList(teams);
	}
	
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		ArrayList<GamePlayerInfo> players = new ArrayList<GamePlayerInfo>();
		for (PlayerEntryView pev : playerView.getAllInputs()) {
			players.add(pev.getPlayerInfo());
		}
		
		outState.putSerializable("playerList", players);
	}
	
	@Override
	public void onRestoreInstanceState(Bundle inState) {
		super.onRestoreInstanceState(inState);
		
		@SuppressWarnings("unchecked")
		ArrayList<GamePlayerInfo> players = (ArrayList<GamePlayerInfo>)inState.getSerializable("playerList");
		
		playerView.setPlayerInfo(players);
	}
	
	
	private void setLocationList(List<String> locationList) {
		if (locationList == null) {
			locationList = new ArrayList<String>();
		}
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, locationList);
		locationView.setAdapter(adapter); 
	}
	
	
	private void setScenarioList(List<String> scenarioList) {
		if (scenarioList == null) {
			scenarioList = new ArrayList<String>();
		}
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, scenarioList);
		scenarioView.setAdapter(adapter); 
	}
}
